#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int abs(int n)
    {
        return n > 0 ? n : -n;
    }
    vector<vector<int>> differenceOfDistinctValues(vector<vector<int>>& grid) {
        unordered_map<int, unordered_map<int, int>> hash;
        int n = grid.size(), m = grid[0].size();
        vector<vector<int>> res(n, vector<int>(m, 0));
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                res[i][j] = hash[i - j].size();
                hash[i - j][grid[i][j]]++;
            }
        }
        hash.clear();
        for (int i = n - 1; i >= 0; i--)
        {
            for (int j = m - 1; j >= 0; j--)
            {
                res[i][j] = abs(res[i][j] - hash[i - j].size());
                hash[i - j][grid[i][j]]++;
            }
        }
        return res;
    }
};